package com.kelai.task.quartz;

import org.quartz.Trigger.TriggerState;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.kelai.domain.AbstractEntity;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.Scheduler;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Map;

@Entity
@Table(name = "T_QUARTZ_CONFIG" , schema = AbstractEntity.DB_SCHEMA)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class QuartzConfigEntity extends AbstractEntity {

    /**
     * 任务名称
     */
    private String jobName;

    /**
     * 分组名称
     */
    private String groupName = Scheduler.DEFAULT_GROUP;

    /**
     * job类path名称
     */
    private String classPath;

    /**
     * 指向方法
     */
    private String targetMethod = "execute";

    /**
     * 是否为串行
     */
    private Boolean isSerial = Boolean.TRUE;

    /**
     * 库伦表达式
     */
    private String cronExpression;
    /**
     * 任务描述
     */
    private String description;

    /**
     * job运行参数
     */
    private String parameters;

    /**
     * 运行状态{NONE, NORMAL, PAUSED, COMPLETE, ERROR, BLOCKED}
     */
    @Transient
    private TriggerState jobStatus;


    public TriggerState getJobStatus() {
        return jobStatus;
    }

    public void setJobStatus(TriggerState jobStatus) {
        this.jobStatus = jobStatus;
    }


    public Map<String, Object> getParameterMap() {
        if (StringUtils.isNotEmpty(parameters)) {
            return JSONObject.parseObject(parameters, new TypeReference<Map<String, Object>>() {
            });
        } else {
            return Maps.newHashMap();
        }
    }

    public Class<?> obtainCls() throws ClassNotFoundException {
        Class<?> cls = Class.forName(classPath);
        return cls;
    }

    public Class<? extends Job> obtainJobCls() throws ClassNotFoundException {
        Class<?> cls = this.obtainCls();
        if (Job.class.isAssignableFrom(cls)) {
            return (Class<? extends Job>) cls;
        }
        return null;

    }


}
